//
//  HZSearchTool.m
//  HZTC_Stock
//
//  Created by MayerF on 17/3/20.
//  Copyright © 2017年 MayerF. All rights reserved.
//

#import "HZSearchTool.h"
#import "QuoteLvOper.h"
#import "SQLTools.h"

extern QUOTELV_OPER *g_pQuoteOper;
extern sqlite3*	g_pDatabase;

typedef void(^resultBack)(NSArray *);

@interface HZSearchTool()
@property (nonatomic, strong)NSMutableArray *pQianResultArray;
@property (nonatomic, strong)NSMutableArray *pZhongResultArray;
@property (nonatomic, strong)NSMutableArray *pHouResultArray;
@property (nonatomic, strong)resultBack result;

@property (nonatomic, strong)NSMutableArray *pHistory;
@end

@implementation HZSearchTool
- (NSMutableArray *)pQianResultArray
{
    if (!_pQianResultArray) {
        _pQianResultArray = [NSMutableArray array];
    }
    return _pQianResultArray;
}
- (NSMutableArray *)pZhongResultArray
{
    if (!_pZhongResultArray) {
        _pZhongResultArray = [NSMutableArray array];
    }
    return _pZhongResultArray;
}
- (NSMutableArray *)pHouResultArray
{
    if (!_pHouResultArray) {
        _pHouResultArray = [NSMutableArray array];
    }
    return _pHouResultArray;
}
- (NSMutableArray *)pHistory
{
    if (!_pHistory) {
        _pHistory = [NSMutableArray array];
    }
    return _pHistory;
}

+ (instancetype)shareSearchTool
{
    static HZSearchTool *pSearchTool = nil;
    @synchronized (self) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            pSearchTool = [[HZSearchTool alloc] init];
        });
    }
    
    return pSearchTool;
}

+ (void)searchStockDictWithSearchInfo:(NSString *)searchInfo
                              success:(void(^)(NSArray *result))success
{
    [HZSearchTool shareSearchTool].result = success;;
    char *sql = Tools_Malloc(5120);
    [self findStockEx:[searchInfo UTF8String] withDes:sql];
    Tools_Free(&sql);
}
#pragma mark ==================
#pragma mark 规则查找股票
+ (void)findStockEx:(char*)aCode withDes:(char*)aDes
{
    [self findStockEx:aCode withDes:aDes withType:FIND_STOCK_MODE_FIND];
}

+ (void)findStockEx:(char*)aCode withDes:(char*)aDes withType:(int)type
{
    NSInteger nLen = strlen(aCode);
    if (nLen > 0) {
        char c = aCode[0];
        if (c=='*' || (c>='A' && c<='Z') || nLen == 6) {
            if (type == FIND_STOCK_MODE_OWN) {
                sprintf(aDes,"select * from qdic where (code like '%s%%' or abb like '%s%%') and marketid<>%d order by type,marketid,code limit 0,100",aCode,aCode,6);
            }else {
                sprintf(aDes,"select * from qdic where (code like '%s%%' or abb like '%s%%') and type=2 and (marketid=1 or marketid=2) order by type,marketid,code  limit 0,40",aCode,aCode);
            }
            [self excuteSql_PY:aDes];
        }else {
            switch (nLen) {
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                {
                    char *pCode = aCode;
                    if (nLen ==4) {
                        if(aCode[0] == '1'){
                            pCode = "601";
                        }
                    }
                    //后
//                    sprintf(aDes, "select * from qdic where code like");
//                    [self setCode:2 withCode:pCode withDes:aDes];
//                    sprintf(aDes, "%s%s",aDes," order by code limit 0,40");//
//                    [self find_HOU:aDes withResult:[HZSearchTool shareSearchTool].pHouResultArray];
                    //前
                    sprintf(aDes, "select * from qdic where code like");
                    [self setCode:0 withCode:pCode withDes:aDes];
                    sprintf(aDes, "%s%s", aDes, " and type=2 and (marketid=1 or marketid=2)");
                    sprintf(aDes, "%s%s",aDes," order by code limit 0,40");
                    [self find_QIAN:aDes withResult:[HZSearchTool shareSearchTool].pQianResultArray];
                    //中
//                    sprintf(aDes, "select * from qdic where code like");
//                    [self setCode:1 withCode:pCode withDes:aDes];
//                    sprintf(aDes, "%s%s",aDes," order by code limit 0,40");
//                    [self find_ZHONG:aDes withResult:[HZSearchTool shareSearchTool].pZhongResultArray];
                }
                    break;
                    
                default:
                    [HZSearchTool shareSearchTool].result(@[]);
                    break;
            }
        }
    }
}

+ (void)setCode:(int)nIndex withCode:(char*)aCode withDes:(char*)aDes
{
    switch (nIndex) {
        case 0://前匹配
        {
            sprintf(aDes,"%s'%s",aDes,aCode);
            sprintf(aDes,"%s%s",aDes,"%'");
        }
            break;
        case 1://中匹配
        {
            sprintf(aDes,"%s%s",aDes,"'%");
            sprintf(aDes,"%s%s",aDes,aCode);
            sprintf(aDes,"%s%s",aDes,"%'");
        }
            break;
        case 2://后匹配
        {
            sprintf(aDes,"%s%s",aDes,"'%");
            sprintf(aDes,"%s%s'",aDes,aCode);
        }
            break;
        default:
            printf("\n setCode is error");
            break;
    }
}

+ (void)excuteSql_PY:(char*)aSql
{
    __block char *pSql;
    int nLen = strlen(aSql);
    pSql = Tools_Malloc(nLen+2);
    memcpy(pSql, aSql, nLen);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSMutableArray *codeArray = [[NSMutableArray alloc] initWithCapacity:20];
        /*查询*/  //SQL
        sqlite3_stmt *statement;
        
        int nOwnCount =  QuoteLvOper_GetOwnCount(g_pQuoteOper);
        char *pOwnDate = QuoteLvOper_GetAllOwnCode(g_pQuoteOper);
        
        char hu[]={"(沪)"};
        char gang[]={"(港)"};
        
        if(sqlite3_prepare_v2(g_pDatabase, pSql, -1, &statement, NULL) == SQLITE_OK) {
            sqlite3_exec(g_pDatabase,"BEGIN TRANSACTION",0,0,0);  //事务开始
            char sBuf[128];
            char sName[32];
            while (sqlite3_step(statement) == SQLITE_ROW)
            {
                memset(sName, 0, 32);
                memcpy(sName, (char*)sqlite3_column_text(statement, FIELD_INDEX_NAME), strlen((char*)sqlite3_column_text(statement, FIELD_INDEX_NAME)));
                
                char *mark=(char *)sqlite3_column_text(statement, FIELD_INDEX_MARKETID);
                int nMark = atoi(mark);
                if (nMark == 6) {//港股
                    strcat(sName,gang);
                }else if(nMark == 24){//沪港通
                    strcat(sName,hu);
                }
                
//                sprintf(sBuf, "%s %s %s", (char*)sqlite3_column_text(statement, FIELD_INDEX_CODE), sName, (char*)sqlite3_column_text(statement, FIELD_INDEX_ABB));
                //添加到列表
                MYSearchResultModel *model = [MYSearchResultModel new];
                model.m_stockName = [NSString stringWithUTF8String:sName];
                model.m_stockCode = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, FIELD_INDEX_CODE)];
                model.n_TradeId = sqlite3_column_int(statement, FIELD_INDEX_MARKETID);
                model.m_isSelected = [HZNetworkTool networkIsOwnStock:model.m_stockCode WithMarketId:model.n_TradeId];
                [codeArray addObject:model];
            }
            
            sqlite3_exec(g_pDatabase,"COMMIT",0,0,0); //COMMIT
            sqlite3_finalize (statement);
        }
        //SQL
        dispatch_async(dispatch_get_main_queue(), ^{
            [HZSearchTool shareSearchTool].result(codeArray);
        });
    });
}

+ (void)find_HOU:(char*)aSql withResult:(NSMutableArray *)result
{
    NSCondition *codition = [NSCondition new];
    [codition lock];
    [self excuteSql:aSql withDes:result withType:0];
    [codition unlock];
    [codition signal];
}

+ (void)find_ZHONG:(char*)aSql withResult:(NSMutableArray *)result
{
    NSCondition *codition = [NSCondition new];
    [codition lock];
    [self excuteSql:aSql withDes:result withType:1];
    [codition unlock];
    [codition signal];
}

+ (void)find_QIAN:(char*)aSql withResult:(NSMutableArray *)result
{
    NSCondition *codition = [NSCondition new];
    [codition lock];
    [self excuteSql:aSql withDes:result withType:2];
    [codition unlock];
    [codition signal];
}
#pragma mark=================================
#pragma mark 优化后
+ (void)excuteSql:(char*)aSql withDes:(NSMutableArray*)aDesArr withType:(int)aType
{
    [aDesArr removeAllObjects];
    __block char *pSql;
    int nLen = strlen(aSql);
    pSql = Tools_Malloc(nLen+2);
    memcpy(pSql, aSql, nLen);
    sqlite3 *b_g_pDatabase = g_pDatabase;
    dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        /*查询*/  //SQL
        sqlite3_stmt *statement;
        char hu[]={"(沪)"};
        char gang[]={"(港)"};
        
        if(sqlite3_prepare_v2(b_g_pDatabase, pSql, -1, &statement, NULL) == SQLITE_OK)
        {
            sqlite3_exec(b_g_pDatabase,"BEGIN TRANSACTION",0,0,0);  //事务开始
            char sBuf[128];
            char sName[32];
            while (sqlite3_step(statement) == SQLITE_ROW)
            {
                memset(sName, 0, 32);
                memcpy(sName, (char*)sqlite3_column_text(statement, FIELD_INDEX_NAME), strlen((char*)sqlite3_column_text(statement, FIELD_INDEX_NAME)));
                
                char *mark=(char *)sqlite3_column_text(statement, FIELD_INDEX_MARKETID);
                int nMark = atoi(mark);
                if (nMark == 6) {//港股
                    strcat(sName,gang);
                }else if(nMark == 24){//沪港通
                    strcat(sName,hu);
                }
                
//                sprintf(sBuf, "%s %s %s %s %s", (char*)sqlite3_column_text(statement, FIELD_INDEX_CODE), sName, (char*)sqlite3_column_text(statement, FIELD_INDEX_ABB),[[NSString stringWithFormat:@"%d",sqlite3_column_int(statement, FIELD_INDEX_MARKETID)] UTF8String],[[NSString stringWithFormat:@"%d",sqlite3_column_int(statement, FIELD_INDEX_TYPE)] UTF8String]);
                
                MYSearchResultModel *model = [MYSearchResultModel new];
                model.m_stockName = [NSString stringWithUTF8String:sName];
                model.m_stockCode = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, FIELD_INDEX_CODE)];
                model.n_TradeId = sqlite3_column_int(statement, FIELD_INDEX_MARKETID);
                model.m_isSelected = [HZNetworkTool networkIsOwnStock:model.m_stockCode WithMarketId:model.n_TradeId];
                //添加到列表
                [aDesArr addObject:model];
            }
            sqlite3_exec(b_g_pDatabase,"COMMIT",0,0,0); //COMMIT
            sqlite3_finalize (statement);
        }
        //SQL
        dispatch_async(dispatch_get_main_queue(), ^{
            [self handleTempData:aDesArr];
            Tools_Free(&pSql);
        });
    });
}

+ (void)handleTempData:(NSArray *)tempData
{
//    if ([HZSearchTool shareSearchTool].pQianResultArray.count) {
//        NSMutableArray *result = [NSMutableArray array];
        
//        [result addObjectsFromArray:[HZSearchTool shareSearchTool].pQianResultArray];
//        [result addObjectsFromArray:[HZSearchTool shareSearchTool].pHouResultArray];
//        [result addObjectsFromArray:[HZSearchTool shareSearchTool].pHouResultArray];
        
        [HZSearchTool shareSearchTool].result(tempData);
//    }
}

#pragma mark -
#pragma mark history
// 历史记录相关
+ (void)searchAddStockHistory:(MYSearchResultModel *)stock
{
    NSData *oldData = [MYCommonTool shareToolReadFileName:@"historyStock" readFileType:KReadFileDataType];
    NSArray *result = [NSKeyedUnarchiver unarchiveObjectWithData:oldData];
    NSMutableArray *tempArray = [NSMutableArray array];
    [tempArray addObjectsFromArray:result];
    __block BOOL isExist = NO;
    [tempArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        MYSearchResultModel *oldModel = (MYSearchResultModel *)obj;
        if ([oldModel.m_stockCode isEqualToString:stock.m_stockCode] && (oldModel.n_TradeId == stock.n_TradeId)) {
            isExist = YES;
            *stop = YES;
        }
    }];
    if (isExist) { return;}
    [tempArray insertObject:stock atIndex:0];
    if (tempArray.count > 7) { //默认5条历史记录
        [tempArray removeLastObject];
    }
    NSData *tempData = [NSKeyedArchiver archivedDataWithRootObject:tempArray];
    [MYCommonTool shareToolWriteToFile:@"historyStock" content:tempData];
}
+ (NSArray *)searchGetHistoryStock
{
    NSData *tempData = [MYCommonTool shareToolReadFileName:@"historyStock" readFileType:KReadFileDataType];
    NSArray *tempArray = [NSKeyedUnarchiver unarchiveObjectWithData:tempData];
    for (MYSearchResultModel *model in tempArray) {
        model.m_isSelected = [HZNetworkTool networkIsOwnStock:model.m_stockCode WithMarketId:model.n_TradeId];
    }
    return tempArray;
}
+ (void)searchDeleteHistoryStock
{
    [MYCommonTool shareToolWriteToFile:@"historyStock" content:[NSArray array]];

}

@end
